import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'dart:convert';

import 'package:package_info_plus/package_info_plus.dart';

class AppUpdateUtil {
  String? url;

  Future<Map?> getVersion() async {
    var parm = {'appType': '1'};
    var r = await HttpUtil.instance
        .getDio()
        .post(HttpApi.updateApp, data: parm,options: PostRequest.urlencodedHeader);
    Map<String, dynamic> map = json.decode(r.data.toString());

    if (map['status'] == "100") {
      var netVersion = map["version"];
      url = map["url"];
      return await checkVersion(map);
    } else {
      return null;
    }
  }

  Future<Map?> checkVersion(Map onLineMap) async {
    var packageInfo = await PackageInfo.fromPlatform();
    String appname = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String localVersion = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;

    // print('$appname' + '  $packageName' + '  $localVersion' + '  $buildNumber');
    SpUtil.putString(Constant.locaVersion, localVersion);
    SpUtil.putString(Constant.applicationId, packageName);
    var onLineVersion = onLineMap['version'];
    // print(localVersion + 'old <---   ---> new' + onLineVersion);
    if (compareVersion(onLineVersion, localVersion) > 0) {
      return onLineMap;
    } else {
      return null;
    }
  }

  Future<String> localVersion() async {
    var packageInfo = await PackageInfo.fromPlatform();

    var localVersion = packageInfo.version;
    return localVersion;
  }

  /// * 版本号对比，0代表相等，1代表version1大于version2，-1代表version1小于version2
  /// * @param version1
  /// * @param version2
  ///* @return
  static int compareVersion(String version1, String version2) {
    if (version1 == version2) {
      return 0;
    }

    List<String> version1Array = version1.split(".");
    List<String> version2Array = version2.split(".");
    int index = 0;
    int minLen = min(version1Array.length, version2Array.length);
    int diff = 0;
    while (index < minLen &&
        (diff = int.parse(version1Array[index], radix: 10) -
                int.parse(version2Array[index], radix: 10)) ==
            0) {
      index++;
    }

    if (diff == 0) {
      for (int i = index; i < version1Array.length; i++) {
        if (int.parse(version1Array[i]) > 0) {
          return 1;
        }
      }
      for (int i = index; i < version2Array.length; i++) {
        if (int.parse(version2Array[i]) > 0) {
          return -1;
        }
      }
      return 0;
    } else {
      return diff > 0 ? 1 : -1;
    }
  }
}
